﻿using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    public class ChangeFontsEditor
    {

        [MenuItem("CGFramework/替换自定义字体请在字体上右键", priority = -601)]
        private static void Tip() { }

        [MenuItem("Assets/所有 Prefab 使用该字体")]
        public static void ChangeAllPrefabsWithCustomFont()
        {
            Font[] fonts = Selection.GetFiltered<Font>(SelectionMode.Assets);
            if (fonts.Length > 1)
            {
                Debug.LogError($"只能选择一个字体");
                return;
            }
            _ChangeAllPrefabsTextFont(fonts[0]);
        }

        [MenuItem("CGFramework/全部换回默认字体", priority = -600)]
        private static void ChangeAllPrefabsWithDefaultFont()
        {
            string name = "LegacyRuntime";
            Font font = null;
            Object[] allBuiltinResources = Resources.FindObjectsOfTypeAll(typeof(Font));
            Debug.Log("=== 查找内置字体列表 ===");
            foreach (Object obj in allBuiltinResources)
            {
                if (obj != null)
                {
                    Font _font = obj as Font;
                    Debug.Log("内置字体：" + _font);
                    if (_font.name.Contains(name))
                    {
                        font = _font;
                        break;
                    }
                }
            }
            if (font == null)
            {
                Debug.LogError($"字体加载失败，请检查名字是否正确：{name}");
                return;
            }
            _ChangeAllPrefabsTextFont(font);
        }

        private static void _ChangeAllPrefabsTextFont(Font font)
        {
            bool confirm = EditorUtility.DisplayDialog("警告", "即将遍历项目所有Prefab上所有Text组件进行替换，此动作不可逆，是否确定执行？", "确定执行", "取消");
            if (!confirm) return;

            string[] prefabGUIDs = AssetDatabase.FindAssets("t:Prefab");
            int count = 0;
            int total = prefabGUIDs.Length;

            try
            {
                for (int i = 0; i < total; i++)
                {
                    string guid = prefabGUIDs[i];
                    string path = AssetDatabase.GUIDToAssetPath(guid);
                    GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                    if (prefab == null) continue;

                    // 显示进度条，带取消按钮
                    if (EditorUtility.DisplayCancelableProgressBar("替换字体进度", $"处理中: {path}", (float)i / total))
                    {
                        Debug.LogWarning("用户取消了字体替换操作");
                        break;
                    }

                    GameObject instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
                    bool modified = false;
                    Text[] texts = instance.GetComponentsInChildren<Text>(true);
                    foreach (Text text in texts)
                    {
                        if (text.font != font)
                        {
                            Undo.RecordObject(text, "Replace Font");
                            text.font = font;
                            modified = true;
                            count++;
                        }
                    }

                    if (modified)
                    {
                        PrefabUtility.SaveAsPrefabAsset(instance, path);
                        Debug.Log($"替换字体：{path}");
                    }

                    GameObject.DestroyImmediate(instance);
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            Debug.Log("替换完成，共替换Text组件数量: " + count);
        }
    }
}
